import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_getx/core/getx/control/cart_control.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:url_strategy/url_strategy.dart';

import 'core/getx/control/locale_control.dart';
import 'core/getx/control/theme_control.dart';
import 'core/init.dart';
import 'core/utils/device_utils.dart';
import 'core/utils/handle_error_utils.dart';
import 'res/strings/translation_service.dart';
import 'routers.dart';
import 'ui/not_found_page.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  setPathUrlStrategy();

  await startInit();

  /// 异常处理
  handleError(runApp(const MyApp()));
  /// 隐藏状态栏。为启动页、引导页设置。完成后修改回显示状态栏。
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: [SystemUiOverlay.bottom]);
  //SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark); //设置全局状态栏文字颜色

}

class MyApp extends StatelessWidget {

  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _buildMaterialApp();
  }

  Widget _buildMaterialApp() {
    Get.put(CartControl());
    final LocaleControl localeControl = Get.put(LocaleControl());
    final ThemeControl themeControl = Get.put(ThemeControl());

    return ScreenUtilInit(
        designSize: const Size(360, 640),
        builder: () => GetMaterialApp(
          title: 'Swanshop',
          unknownRoute: GetPage(name: '/404', page: () => const NotFoundPage()),
          initialRoute: '/',
          getPages: routerPages,
          locale: localeControl.locale,
          fallbackLocale: localeControl.locale,
          translations: TranslationService(),
          theme: themeControl.getTheme(),
          darkTheme: themeControl.getTheme(true),
          // debugShowCheckedModeBanner: false, // 去除右上角debug的标签
          builder: (BuildContext context, Widget? child) {
            /// 仅针对安卓
            if (Device.isAndroid) {
              /// 切换深色模式会触发此方法，这里设置导航栏颜色
              themeControl.setSystemNavigationBar(Get.rootController.themeMode ?? ThemeMode.system);
            }

            /// 保证文字大小不受手机系统设置影响 https://www.kikt.top/posts/flutter/layout/dynamic-text/
            return MediaQuery(
              data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
              child: FlutterSmartDialog(child: child,),
            );
          },
          //restorationScopeId: 'app',
        ));
  }
}
